#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(OS_ANDROID)||defined(OS_LINUX_SOC)
#include <err.h>
#endif
#include <libmslog/mslog.h>
#include <libmscommon/mscommon.h>
#include "msprotocol.h"

#define  FLAG "fifo"

static int fifo_open(URLContext *h)
{
	char *filename=h->url;
	MSFIFOBLOCKContext * pmsfifo_ctt= msfifoblock_api_init(ms_u32 ms_in size,filename);

	h->fd =(pmsfifo_ctt);
	return h->fd ;
}

static int fifo_read(URLContext *h, unsigned char *buf, int size)
{
	MSFIFOBLOCKContext * pmsfifo_ctt=(MSFIFOBLOCKContext * ) h->fd;
	ms_s32 len=ms_min(size, msfifoblock_api_sizeused(pmsfifo_ctt));
	msfifoblock_api_out(pmsfifo_ctt, buf, len, ms_null);
	return 0;
}

static int fifo_write(URLContext *h, unsigned char *buf, int size)
{
	MSFIFOBLOCKContext * pmsfifo_ctt=(MSFIFOBLOCKContext * ) h->fd;
	if( msfifoblock_api_sizeleft(pmsfifo_ctt)<size) {/* No Space left */
		msfifoblock_api_flowoverreset(pmsfifo_ctt);	
		ms_waring("[%s]Waring:pmsfifo_ctt overflow,reset ",pmsfifo_ctt->name);
	}
	msfifoblock_api_in(pmsfifo_ctt, buf, size, ms_null);
	return 0;
}

static int fifo_close(URLContext *h)
{
	MSFIFOBLOCKContext * pmsfifo_ctt=(MSFIFOBLOCKContext * ) h->fd;
	msfifoblock_api_deinit(&pmsfifo_ctt);
	return 0;
}

URLProtocol ffurl_fifo_protocol = {
	.name		= PTLNAME_FIFO,
	.longname	= PTLDES_FIFO,		
	.url_open	= fifo_open,
	.url_read	= fifo_read,
	.url_write	= fifo_write,
	.url_close	= fifo_close,
};
